import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { IProject } from '../model/interfaces'
import { projectsApi } from '../api/projectsApi'

interface IProjectsState {
  projects: IProject[]
}

const initialState: IProjectsState = {
  projects: []
}

export const projectsSlice = createSlice({
  name: 'projects',
  initialState,
  reducers: {
    setProjects(state, {payload}: PayloadAction<IProject[]>) {
      state.projects = payload
    }
  },
  extraReducers: (builder) => {
    builder.addMatcher(projectsApi.endpoints?.getProjects.matchFulfilled, (state, {payload}: PayloadAction<IProject[]>) => {
      state.projects = payload
    })
  }
})

export const projectsActions = projectsSlice.actions
export const projectsReducer = projectsSlice.reducer
